
package com.funo.government.info.view;

import java.io.File;
import java.util.Date;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.funo.government.info.R;
import com.funo.government.info.constant.Constant;

public class FileManagerActivity extends BaseActivity {

    private ListView lvFile;

    private SharedPreferences preferences;

    private DownloadManager downloadManager;

    private LayoutInflater mInflater;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_manager);
        lvFile = (ListView) findViewById(R.id.lvFile);
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        mInflater = getLayoutInflater();
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String downloadIds = preferences.getString(Constant.PRE_KEY_DOWNLOAD_IDS, "");
        if (!TextUtils.isEmpty(downloadIds)) {
            String[] idsStr = downloadIds.split(",");
            long[] ids = new long[idsStr.length];
            for (int i = 0; i < idsStr.length; i++) {
                ids[i] = Long.parseLong(idsStr[i]);
            }
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(ids).setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cursor = downloadManager.query(query);
            lvFile.setAdapter(new FileListAdapter(this, cursor));
        }
    }

    public void openFileFromSDCard(String fileStr, String mimeType) {
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        File file = new File(fileStr);
        intent.setDataAndType(Uri.fromFile(file), mimeType);
        try {
            startActivity(intent);
        } catch (android.content.ActivityNotFoundException ex) {
            String tip;
            if ("application/msword".equalsIgnoreCase(mimeType)
                    || "application/vnd.ms-excel".equalsIgnoreCase(mimeType)
                    || "application/vnd.ms-powerpoint".equalsIgnoreCase(mimeType)) {
                tip = getString(R.string.tip_file_cannot_open_office);
            } else if ("application/pdf".equalsIgnoreCase(mimeType)) {
                tip = getString(R.string.tip_file_cannot_open_pdf);
            } else {
                tip = getString(R.string.tip_file_cannot_open_common);
            }
            Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
        }
    }

    private class FileListAdapter extends CursorAdapter {

        public FileListAdapter(Context context, Cursor c) {
            super(context, c, true);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ViewHolder vh = (ViewHolder) view.getTag();
            displayData(cursor, vh);
        }

        private void displayData(Cursor cursor, ViewHolder vh) {
            String filepath = cursor.getString(cursor
                    .getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));

            String fileName = filepath.substring(filepath.lastIndexOf("/") + 1);
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            vh.tvFileName.setText(fileName);

            long time = cursor.getLong(cursor
                    .getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
            vh.tvDownloadTime.setText(getString(R.string.download_time, new Date(time)));
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = mInflater.inflate(R.layout.item_file_list, null);
            ViewHolder vh = new ViewHolder();
            vh.tvFileName = (TextView) view.findViewById(R.id.tvFileName);
            vh.tvDownloadTime = (TextView) view.findViewById(R.id.tvDownloadTime);
            view.setTag(vh);
            final String filepath = cursor.getString(cursor
                    .getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
            final String mimeType = cursor.getString(cursor
                    .getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    openFileFromSDCard(filepath, mimeType);
                }
            });
            displayData(cursor, vh);
            return view;
        }

    }

    private class ViewHolder {
        TextView tvFileName;

        TextView tvDownloadTime;

    }
}
